/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.landmark;

import java.awt.BorderLayout;
import java.awt.Component;
import java.io.*;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import org.htmlparser.Parser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

/**
 *
 * @author computer
 */
public class Util {

    public static HelperBean helperBean;

    public static HelperBean getHelperBean() {
        return helperBean;
    }

    public static void setHelperBean(HelperBean helerBean) {
        Util.helperBean = helerBean;
    }

    /**
     *
     * @param className
     * @param aPanel
     */
    public static void setComponents(Class<?> className, JPanel aPanel) {
        aPanel.setVisible(false);
        aPanel.removeAll();
        try {
            Constructor<?>[] constrc = className.getConstructors();
            for (Constructor cons : constrc) {
                Component rf = (Component) cons.newInstance();
                aPanel.setLayout(new BorderLayout());
                aPanel.add(rf, BorderLayout.CENTER);
                aPanel.setVisible(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(aPanel, e.getStackTrace());
        }
    }

    public static void taskCompleteMsg(String status) {
        JOptionPane.showMessageDialog(Util.getHelperBean().getDataPanel(), status);
        Util.getHelperBean().setTerminateCurrentProcess(false);
    }

    /**
     *
     * @param aUrl
     * @return
     */
    public static Document getDocumentFromUrl(String aUrl) throws Exception {
        Document doc = null;
        doc = Jsoup.connect(aUrl).timeout(100 * 1000).get();// get the page with this url

        return doc;
    }

    public static JTextArea createOutputFile(String catalogName) {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yy");

        String fileName = "./outputs/" + catalogName + "-" + formatter.format(date) + ".csv";
        String errors = "./outputs/" + catalogName + "-Errors-" + formatter.format(date) + ".csv";

        JTextArea txtArea = (JTextArea) Util.getHelperBean().getComponent();
        txtArea.setText(null);//Initialise text area with blank
        File mainFile = new File(fileName);
        File errorFile = new File(errors);
        getHelperBean().setOutputFile(mainFile);
        getHelperBean().setErrorFile(errorFile);
        return txtArea;
    }

    /**
     * Takes an URL and returns the constructed Html data in StringBuilder
     *
     * @param aUrl
     * @return
     * @throws MalformedURLException
     * @throws IOException
     */
    public static StringBuilder readUrl(String aUrl) throws MalformedURLException, IOException {
        URL oracle = new URL(aUrl);
        StringBuilder sbUrlData = new StringBuilder();
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            sbUrlData.append(inputLine);
        }
        in.close();
        return sbUrlData;
    }

    /**
     * This method returns a org.htmlparser.Parser taking the inputs and getting
     * the page from the given URL
     *
     * @param aUrl
     * @param inputHTML
     * @return
     */
    public static Parser getParserFromUrl(String aUrl, Document aDoc) throws Exception {
        //System.out.println("Process model : " + aUrl);
        Parser parser = null;
        if (aDoc == null || "null".equals(aDoc)) {
            aDoc = getDocumentFromUrl(aUrl);
        }
        parser = new Parser(aUrl);
        parser.setInputHTML(aDoc.toString());
        parser.setEncoding("UTF-8");
        getHelperBean().setInputHTML(aDoc);
        return parser;
    }

    /**
     *
     * @param aDirName
     */
    public static void createDirectory(String aDirName) {
        try {
            JTextArea txtArea = ((JTextArea) getHelperBean().getComponent());
            File file = new File(aDirName);
            file.mkdirs();
            if (file.isDirectory()) {
                txtArea.append("\n Directory " + file.getAbsolutePath() + " already exits");
            } else {
                txtArea.append("\n Directory " + file.getAbsolutePath() + " created");
            }
            txtArea.paintImmediately(txtArea.getVisibleRect());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param imageUrl
     * @param aDir
     * @param attrName
     */
    public static void saveImage(String imageUrl, String aDir, String attrName) throws Exception {
        String fileName = "";
        if (attrName == null) {
            if (imageUrl.indexOf("?") != 0 && imageUrl.indexOf("?") != -1) {
                fileName = imageUrl.substring(imageUrl.lastIndexOf("/"), imageUrl.indexOf("?"));
            } else {
                fileName = imageUrl.substring(imageUrl.lastIndexOf("/"), imageUrl.length());
            }
        } else {
            int ampIndex = imageUrl.indexOf("&"); // going to be specific to chefdesign type of urls where there is only one & in the URL
            if (ampIndex == -1) {
                ampIndex = imageUrl.length();
            }
            //Example of an url is "http://www.chefdesigns.com/product2/ModalControls/ShowZoom.aspx?ImageName=NP12RD.tif&ObjectID=142047&ImageType=4"
            fileName = imageUrl.substring(imageUrl.indexOf(attrName) + attrName.length() + 1, ampIndex);//image name starts after attrName.length + =
        }
        URL url = new URL(imageUrl);

        InputStream is = url.openStream();

        OutputStream os = new FileOutputStream(aDir + "/" + fileName);

        byte[] b = new byte[2048];
        int length;

        while ((length = is.read(b)) != -1) {
            os.write(b, 0, length);
        }

        is.close();
        os.close();
    }
    static int lineCount = 0;

    public static void getLinesCount(File inputFile) throws Exception {
        if (inputFile.exists()) {
            BufferedReader bf = new BufferedReader(new FileReader(inputFile));
            while (bf.readLine() != null) {
                lineCount++;
            }
            getHelperBean().setLineCount(lineCount);
        }
    }
}
